<template>
  <div class="charts-example-container">
    <div class="page-header">
      <h2>图表示例</h2>
      <p>本页面展示了常用的数据可视化图表</p>
    </div>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>柱状图</h3>
              <el-tag type="primary">基础图表</el-tag>
            </div>
          </template>
          <div class="chart-container" ref="barChartRef"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>折线图</h3>
              <el-tag type="success">基础图表</el-tag>
            </div>
          </template>
          <div class="chart-container" ref="lineChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>饼图</h3>
              <el-tag type="warning">基础图表</el-tag>
            </div>
          </template>
          <div class="chart-container" ref="pieChartRef"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>散点图</h3>
              <el-tag type="info">基础图表</el-tag>
            </div>
          </template>
          <div class="chart-container" ref="scatterChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>综合仪表盘</h3>
              <el-tag type="danger">高级图表</el-tag>
            </div>
          </template>
          <div class="chart-container chart-large" ref="gaugeChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts/core'
import { 
  BarChart, LineChart, PieChart, ScatterChart, GaugeChart 
} from 'echarts/charts'
import {
  TitleComponent, TooltipComponent, GridComponent, LegendComponent,
  ToolboxComponent, DataZoomComponent 
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  BarChart, LineChart, PieChart, ScatterChart, GaugeChart,
  TitleComponent, TooltipComponent, GridComponent, LegendComponent,
  ToolboxComponent, DataZoomComponent, CanvasRenderer
])

// 图表DOM引用
const barChartRef = ref(null)
const lineChartRef = ref(null)
const pieChartRef = ref(null)
const scatterChartRef = ref(null)
const gaugeChartRef = ref(null)

// 图表实例
let barChart = null
let lineChart = null
let pieChart = null
let scatterChart = null
let gaugeChart = null

// 窗口大小变化监听函数
const handleResize = () => {
  barChart?.resize()
  lineChart?.resize()
  pieChart?.resize()
  scatterChart?.resize()
  gaugeChart?.resize()
}

onMounted(() => {
  // 初始化图表
  initBarChart()
  initLineChart()
  initPieChart()
  initScatterChart()
  initGaugeChart()

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  barChart?.dispose()
  lineChart?.dispose()
  pieChart?.dispose()
  scatterChart?.dispose()
  gaugeChart?.dispose()
})

// 初始化柱状图
const initBarChart = () => {
  barChart = echarts.init(barChartRef.value)
  const option = {
    title: {
      text: '近6个月各类收入统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['物业费', '停车费', '维修费', '其他'],
      bottom: '0%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      name: '金额（元）'
    },
    series: [
      {
        name: '物业费',
        type: 'bar',
        data: [32000, 35000, 31000, 33000, 36000, 34000]
      },
      {
        name: '停车费',
        type: 'bar',
        data: [15000, 14000, 15500, 16000, 15800, 16200]
      },
      {
        name: '维修费',
        type: 'bar',
        data: [8000, 9500, 7800, 8200, 9000, 8500]
      },
      {
        name: '其他',
        type: 'bar',
        data: [5200, 4800, 5500, 4900, 5100, 5300]
      }
    ]
  }
  barChart.setOption(option)
}

// 初始化折线图
const initLineChart = () => {
  lineChart = echarts.init(lineChartRef.value)
  const option = {
    title: {
      text: '月度业主投诉数量趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['噪音投诉', '设施损坏', '服务投诉', '其他'],
      bottom: '0%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      name: '投诉次数'
    },
    series: [
      {
        name: '噪音投诉',
        type: 'line',
        data: [12, 15, 10, 8, 9, 7],
        smooth: true
      },
      {
        name: '设施损坏',
        type: 'line',
        data: [8, 6, 9, 7, 5, 6],
        smooth: true
      },
      {
        name: '服务投诉',
        type: 'line',
        data: [5, 7, 6, 8, 4, 3],
        smooth: true
      },
      {
        name: '其他',
        type: 'line',
        data: [3, 4, 5, 2, 3, 4],
        smooth: true
      }
    ]
  }
  lineChart.setOption(option)
}

// 初始化饼图
const initPieChart = () => {
  pieChart = echarts.init(pieChartRef.value)
  const option = {
    title: {
      text: '住户类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: '0%',
      data: ['自住', '出租', '空置', '其他']
    },
    series: [
      {
        name: '住户类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 735, name: '自住' },
          { value: 210, name: '出租' },
          { value: 80, name: '空置' },
          { value: 35, name: '其他' }
        ]
      }
    ]
  }
  pieChart.setOption(option)
}

// 初始化散点图
const initScatterChart = () => {
  scatterChart = echarts.init(scatterChartRef.value)
  
  // 生成随机数据
  const data1 = []
  const data2 = []
  
  for (let i = 0; i < 50; i++) {
    data1.push([
      Math.round(Math.random() * 100),
      Math.round(Math.random() * 100),
      Math.round(Math.random() * 40)
    ])
    data2.push([
      Math.round(Math.random() * 100),
      Math.round(Math.random() * 100),
      Math.round(Math.random() * 20)
    ])
  }
  
  const option = {
    title: {
      text: '各楼栋水电使用对比',
      left: 'center'
    },
    grid: {
      left: '3%',
      right: '7%',
      bottom: '10%',
      containLabel: true
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return `耗水量: ${params.value[0]} 吨<br/>耗电量: ${params.value[1]} 度<br/>人口数: ${params.value[2]} 人`
      }
    },
    xAxis: {
      name: '耗水量（吨）',
      min: 0,
      max: 100,
      axisLine: { show: true },
      splitLine: { show: false }
    },
    yAxis: {
      name: '耗电量（度）',
      min: 0,
      max: 100,
      axisLine: { show: true },
      splitLine: { show: false }
    },
    series: [
      {
        name: 'A区',
        type: 'scatter',
        symbolSize: function(data) {
          return data[2] / 2
        },
        emphasis: {
          focus: 'series',
          label: {
            show: true,
            formatter: function(param) {
              return param.data[2]
            },
            position: 'top'
          }
        },
        data: data1
      },
      {
        name: 'B区',
        type: 'scatter',
        symbolSize: function(data) {
          return data[2] / 2
        },
        emphasis: {
          focus: 'series',
          label: {
            show: true,
            formatter: function(param) {
              return param.data[2]
            },
            position: 'top'
          }
        },
        data: data2
      }
    ],
    legend: {
      data: ['A区', 'B区'],
      bottom: '0%'
    }
  }
  
  scatterChart.setOption(option)
}

// 初始化仪表盘
const initGaugeChart = () => {
  gaugeChart = echarts.init(gaugeChartRef.value)
  
  const option = {
    title: {
      text: '小区关键指标监控',
      left: 'center'
    },
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%'
    },
    toolbox: {
      feature: {
        restore: {},
        saveAsImage: {}
      }
    },
    grid: {
      top: '30%',
      bottom: '10%'
    },
    series: [
      {
        name: '物业费缴纳率',
        type: 'gauge',
        radius: '30%',
        center: ['25%', '50%'],
        detail: { formatter: '{value}%' },
        data: [{ value: 92, name: '物业费缴纳率' }],
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#ff4500'],
              [0.7, '#ffde00'],
              [1, '#5cb85c']
            ]
          }
        }
      },
      {
        name: '小区安全指数',
        type: 'gauge',
        radius: '30%',
        center: ['50%', '50%'],
        detail: { formatter: '{value}%' },
        data: [{ value: 95, name: '小区安全指数' }],
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#ff4500'],
              [0.7, '#ffde00'],
              [1, '#5cb85c']
            ]
          }
        }
      },
      {
        name: '业主满意度',
        type: 'gauge',
        radius: '30%',
        center: ['75%', '50%'],
        detail: { formatter: '{value}%' },
        data: [{ value: 87, name: '业主满意度' }],
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#ff4500'],
              [0.7, '#ffde00'],
              [1, '#5cb85c']
            ]
          }
        }
      }
    ]
  }
  
  gaugeChart.setOption(option)
}
</script>

<style scoped>
.charts-example-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 14px;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.chart-large {
  height: 400px;
}

.mt-20 {
  margin-top: 20px;
}
</style> 